<template>
  <div class="svg-container" ref="svgContainer">
    <div v-html="svgContent"></div>
    <!-- 悬浮卡片 -->
    <div
      v-if="showCard"
      :style="{
        position: 'fixed',
        left: cardPos.x + 10 + 'px',
        top: cardPos.y + 10 + 'px',
        background: 'rgba(28,58,99,0.98)',
        borderRadius: '8px',
        boxShadow: '0 0 30px rgba(11,93,209,0.4)',
        zIndex: 9999,
        color: '#fff',
        padding: '10px 16px'
      }"
    >
    <div v-html="cardContent"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'

const props = defineProps<{
  src: string // svg文件路径
  hotspotInfo?: Record<string, string> // 可选，热点id与内容映射
}>()

const svgContent = ref('')
const showCard = ref(false)
const cardPos = ref({ x: 0, y: 0 })
const cardContent = ref('')
const svgContainer = ref<HTMLElement | null>(null)

const defaultHotspotInfo = {
  hotspot1: '左侧工位信息卡片内容',
  hotspot2: '中间工位信息卡片内容',
  hotspot3: '右侧工位信息卡片内容'
}

const hotspotInfo = props.hotspotInfo || defaultHotspotInfo

// 加载SVG文件内容
async function loadSvg() {
  const res = await fetch(props.src)
  let text = await res.text()
  // 不再移除 <style> 标签，以保证SVG样式正常显示
  // text = text.replace(/<style[\s\S]*?<\/style>/gi, '')
  
  // 移除 <script> 标签（防止内嵌脚本执行出错或产生安全问题）
  text = text.replace(/<script[\s\S]*?<\/script>/gi, '')
  
  // 新增：移除各类动画标签，从根源上防止因动画计算错误导致的报错
  text = text.replace(/<animate[\s\S]*?<\/animate>/gi, '');
  text = text.replace(/<animateTransform[\s\S]*?<\/animateTransform>/gi, '');
  text = text.replace(/<animateMotion[\s\S]*?<\/animateMotion>/gi, '');

  svgContent.value = text
}

function handleEnter(e: MouseEvent) {
  showCard.value = true
  cardPos.value = { x: e.clientX, y: e.clientY }
  // @ts-ignore
  cardContent.value = hotspotInfo[e.target.id] || '未知热点'
}
function handleLeave() {
  showCard.value = false
}

function bindHotspotEvents() {
  // 需要等svg渲染到dom后再绑定
  setTimeout(() => {
    const svg = svgContainer.value?.querySelector('svg')
    if (svg) {
      svg.querySelectorAll('.svg-hotspot').forEach((el: any) => {
        el.addEventListener('mouseenter', handleEnter)
        el.addEventListener('mouseleave', handleLeave)
      })
    }
  }, 100)
}
function unbindHotspotEvents() {
  const svg = svgContainer.value?.querySelector('svg')
  if (svg) {
    svg.querySelectorAll('.svg-hotspot').forEach((el: any) => {
      el.removeEventListener('mouseenter', handleEnter)
      el.removeEventListener('mouseleave', handleLeave)
    })
  }
}

onMounted(async () => {
  await loadSvg()
  bindHotspotEvents()
})
onBeforeUnmount(() => {
  unbindHotspotEvents()
})
watch(svgContent, () => {
  bindHotspotEvents()
})
</script>

<style scoped>
.svg-container {
  width: 100%;
  height: 20vh;
}
.svg-container svg {
  width: 100%;
  height: 100%;
}
</style> 